<template>
  <div class="process-route-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>工艺路线</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" class="filter-form" inline @keyup.enter="handleSearch">
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="请输入工艺路线编号/名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-180">
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="2" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="info" plain>导出</el-button>
      </div>

      <el-table
        :data="rows"
        border
        stripe
        :loading="loading"
        class="process-route-table"
        height="640"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="process_routename" label="工艺路线名称" min-width="160" />
        <el-table-column prop="process_routecode" label="工艺路线编号" min-width="160" />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="工艺路线说明" min-width="220" show-overflow-tooltip />
        <el-table-column prop="remarks" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-divider direction="vertical" />
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, HomeFilled, Menu, Setting } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import https from '@/Http/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface ProcessRouteItem {
  id: number
  process_routecode: string
  process_routename: string
  status: number
  description?: string
  remarks?: string
}

const loading = ref(false)
const rows = ref<ProcessRouteItem[]>([])
const multipleSelection = ref<ProcessRouteItem[]>([])

const pager = reactive({
  page: 1,
  size: 10,
  total: 0,
})

const searchForm = reactive({
  keyword: '',
  status: undefined as number | undefined,
})

const fetchList = async () => {
  loading.value = true
  try {
    const response = await https.Reads.get(`/AManufacturing_process/AProcess_routeShow`, {
      params: {
        process_routenameorcode: searchForm.keyword || undefined,
        status: searchForm.status ?? 0,
        pageindex: pager.page,
        pagesize: pager.size,
      },
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取工艺路线数据失败'))
    }
    const list: ProcessRouteItem[] = payload?.data ?? payload?.Data ?? []
    rows.value = list
    pager.total = payload?.totalCount ?? payload?.TotalCount ?? list.length
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取工艺路线数据失败'))
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pager.page = 1
  fetchList()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = undefined
  pager.page = 1
  fetchList()
}

const onSelectionChange = (val: ProcessRouteItem[]) => {
  multipleSelection.value = val
}

const onPageSizeChange = (size: number) => {
  pager.size = size
  pager.page = 1
  fetchList()
}

const onPageChange = (page: number) => {
  pager.page = page
  fetchList()
}

const router = useRouter()
const handleAdd = () => {
  router.push('/AProcess_routeAddView')
}

// 编辑工艺路线
const handleEdit = (row: ProcessRouteItem) => {
  router.push({
    path: '/AProcess_routeAddView',
    query: { id: row.id }
  })
}

// 删除单个工艺路线
const handleDelete = async (row: ProcessRouteItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工艺路线"${row.process_routename}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await https.Writes.post('/AProcess_route/ProcessRouteDelete', {
      id: row.id
    })
    const payload = extractPayload(response)
    const success = isRequestSuccess(payload)
    const message = getResponseMessage(payload, success ? '删除成功' : '删除失败')
    if (success) {
      ElMessage.success(message)
      fetchList()
    } else {
      ElMessage.error(message)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除工艺路线失败', error)
      ElMessage.error(getErrorMessage(error, '删除失败'))
    }
  }
}

// 批量删除工艺路线
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的工艺路线')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${multipleSelection.value.length} 条工艺路线吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 批量删除
    const deletePromises = multipleSelection.value.map(item =>
      https.Writes.post('/AProcess_route/ProcessRouteDelete', { id: item.id })
        .then(res => extractPayload(res))
        .catch(err => ({ __error: err }))
    )

    const results = await Promise.all(deletePromises)
    let successCount = 0
    const failedMessages: string[] = []

    results.forEach(result => {
      if ('__error' in result) {
        failedMessages.push(getErrorMessage(result.__error, '删除失败'))
        return
      }
      if (isRequestSuccess(result)) {
        successCount += 1
      } else {
        failedMessages.push(getResponseMessage(result, '删除失败'))
      }
    })

    if (successCount > 0) {
      ElMessage.success(`成功删除 ${successCount} 条工艺路线`)
      multipleSelection.value = []
      fetchList()
    }

    if (failedMessages.length) {
      ElMessage.error(failedMessages.join('；'))
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除工艺路线失败', error)
      ElMessage.error(getErrorMessage(error, '批量删除失败'))
    }
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.process-route-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.process-route-page::before {
  content: "";
  position: fixed;
  inset: 0;
  pointer-events: none;
  z-index: 0;
}

.process-route-page > * {
  position: relative;
  z-index: 1;
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  position: relative;
  overflow: hidden;
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.filter-card,
.table-card {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.process-route-table {
  width: 100%;
}

.mt-12 {
  margin-top: 12px;
}

.w-180 {
  width: 180px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
